﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
using Sparkle.MVVM.ActionResults;
using Sparkle.MVVM.Messages;

namespace Sparkle.MVVM
{
    public class Command : ICommand
    {
        private readonly Action _executeAction;

        private readonly Predicate<object> _canExecuteAction;

        private readonly ResultAction<object, object> _resultAction;

        public Command(Action executeAction)
        {
            _executeAction = executeAction;
        }

        public Command(Action executeAction, Predicate<object> canExecuteAction)
        {
            _executeAction = executeAction;
            _canExecuteAction = canExecuteAction;
        }

        public Command(ResultAction<object, object> executeAction)
        {
            _resultAction = executeAction;
        }

        public Command(ResultAction<object, object> executeAction, Predicate<object> canExecuteAction)
        {
            _resultAction = executeAction;
            _canExecuteAction = canExecuteAction;
        }

        #region Implementation of ICommand

        /// <summary>
        /// Defines the method to be called when the command is invoked.
        /// </summary>
        /// <param name="parameter">Data used by the command.  If the command does not require data to be passed, this object can be set to null.</param>
        public void Execute(object parameter)
        {
            if (_executeAction != null)
                _executeAction();

            if (_resultAction != null)
            {
                var result = _resultAction(parameter);
                if (result is IActionResult)
                {
                    (result as IActionResult).Execute();
                }

                if (result is ISendMessage)
                {
                    (result as ISendMessage).Send();
                }
                if (result is IPostMessage)
                {
                    (result as IPostMessage).Post();
                }
            }
        }

        /// <summary>
        /// Defines the method that determines whether the command can execute in its current state.
        /// </summary>
        /// <returns>
        /// true if this command can be executed; otherwise, false.
        /// </returns>
        /// <param name="parameter">Data used by the command.  If the command does not require data to be passed, this object can be set to null.</param>
        public bool CanExecute(object parameter)
        {
            return _canExecuteAction == null || _canExecuteAction(parameter);
        }

        public event EventHandler CanExecuteChanged;

        #endregion
    }

}
